package cn.edu.ctbu.simplescoremanagementsystem.intercepter;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        log.info("session:"+request.getSession().toString());
        Integer code = (Integer)request.getSession().getAttribute(GlobalConst.USER_SESSION_KEY.getMsg());
        log.info("请求api："+request.getRequestURI().toString());
        if (code == null || code.equals("")) {
            code = (Integer)request.getSession().getAttribute(GlobalConst.ADMIN_SESSION_KEY.getMsg());
            if (code == null || code.equals("")) {
                response.sendRedirect("/login/student");
                log.info("请先登录"+request.getRequestURI());
                return false;
            }
        }
        return true;
    }

    @Configuration
    public class WebConfigurer implements WebMvcConfigurer {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new LoginInterceptor())
                    .addPathPatterns("/webapi/**")
                    .excludePathPatterns("/error","/webapi/login/**");
        }
    }

}
